from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status, Body, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from router.route_log import LogRoute
from model.User import UserModel
from common.setting import settings
from common.db_init import get_db
from common.response import ApiResponse, CustomApiResponse, response_code, responseCode
from utils.tool import Page
from paramsModel.user import DelBatch, User
from common.custom_log import my_logger
from .ws import WsEcho
from starlette.endpoints import WebSocketEndpoint
userController = APIRouter(prefix='/user',route_class=LogRoute)


@userController.post("/info", summary="获取用户信息", response_model=CustomApiResponse)
async def getUser(current_user=Depends(UserModel.get_current_user)):
    if not current_user:
        return CustomApiResponse(code=200, message='用户不存在')
    del current_user["hashed_password"]
    return CustomApiResponse(message='success', data=current_user)


@userController.post("/login", response_model=CustomApiResponse)
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user_dict = UserModel.authenticate_user(db, form_data)
    if not user_dict:
        raise HTTPException(status_code=500, detail=CustomApiResponse(message="Incorrect username or password",
                                                                      code=responseCode.Error.value))
    access_token_expires = timedelta(minutes=settings.TOKEN_EXPIRE_MINUTES)
    access_token = UserModel.create_access_token(
        data={"username": user_dict.get('username'), "id": user_dict.get('id')}, expires_delta=access_token_expires
    )
    return CustomApiResponse(message='success', data={
        'user': user_dict,
        'access_token': access_token,
        'token_type': "bearer"
    })


@userController.post("/add")
async def add(user: User, db: Session = Depends(get_db), current_user=Depends(UserModel.get_current_user)):
    try:
        user.password = UserModel.fake_hash_password(user.password)
        user.action_id = current_user.get('id')
        userinfo = UserModel.add_user(db=db, userinfo=user)
        return CustomApiResponse(data={'id': userinfo})
    except Exception as e:
        return CustomApiResponse(message=e.detail, code=responseCode.Error.value)


# 修改用户名
@userController.post("/updateName")
async def updata_name(user: User, db: Session = Depends(get_db)):
    isdone = UserModel.update_user(db, user)
    if isdone is None:
        return CustomApiResponse(message='fail', data=None)
    return CustomApiResponse(message='success', data=None)


# 更新用户信息
@userController.post("/updateInfo", summary='获取用户信息', response_model=CustomApiResponse)
async def updata_info(user: User = Body(...), db: Session = Depends(get_db)):
    try:
        # 去除掉接收值内部是None的
        updatainfo_data = user.model_dump(exclude_none=True)
        if updatainfo_data.get('password'):
            updatainfo_data['password'] = UserModel.fake_hash_password(updatainfo_data.get('password'))
        UserModel.update_userinfo(db, updatainfo_data)
        return CustomApiResponse(message='success')
    except HTTPException as e:
        return CustomApiResponse(message='fail')


# 获取所有用户
@userController.get('/list', summary="分页获取用户列表", response_model=CustomApiResponse)
async def getUserList(page: int = 1, pagesize: int = 10, db: Session = Depends(get_db)):
    pageModel = Page(page=page, pagesize=pagesize)
    userlist = UserModel.get_page_list(db, {'start': pageModel.skip, 'pagesize': pagesize})
    return CustomApiResponse(data=userlist)


# 批量删除
@userController.post('/delBatch', summary="批量删除用户", response_model=CustomApiResponse)
async def delBatch(params: DelBatch, current_user=Depends(UserModel.get_current_user), db: Session = Depends(get_db)):
    if len(params.uids) == 0:
        return CustomApiResponse(code=responseCode.Error.value, message='请选择所需数据')
    my_logger.info(
        f"用户:{current_user.get('id')}-{current_user.get('username')}正在操作批量删除,预删除的uids：{params.uids}！")
    UserModel.del_Batch(uids=params.uids, db=db)
    return CustomApiResponse()


@userController.get('/test')
def test():
    return UserModel.fake_hash_password('123456')
